package com.baidu.config;

import com.baidu.common.Rest;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

// 全局异常捕获
//@ControllerAdvice 返回视图、页面
@RestControllerAdvice // 返回的字符串
public class GlobalHandleController {
    @ExceptionHandler(ConstraintViolationException.class)
    public Rest ValidationException(ConstraintViolationException e){
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        List<String> collect = violations.stream().map(o -> o.getMessage()).collect(Collectors.toList());
        System.out.println(collect);
        return Rest.faild("校验出现异常" + collect.toString());
    }

    @ExceptionHandler(BindException.class)
    public Rest BindException(BindException e){
        FieldError error = e.getFieldError();
        return Rest.faild(error.getDefaultMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Rest MethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        return Rest.faild(e.getMessage());
    }
}
